export default {
	data () {
		return {
			socket:"",
            websocket:"ws://118.24.11.96:9502",
		}
	},
    mounted(){
        window.addEventListener('beforeunload', this.handleBrowserRefresh);  
    },
    destroyed() {
        window.removeEventListener('beforeunload', this.handleBrowserRefresh);
    },
	methods: {
        handleBrowserRefresh(){
            alert(1)
            this.stop()
        },
		broadcast(text){
			const speech = new SpeechSynthesisUtterance(text);
            speech.volume = 1; // 设置音量
            window.speechSynthesis.speak(speech);
		},
        stop(){
            window.speechSynthesis.cancel()
        },
		connect(){
            if(typeof(WebSocket) === "undefined"){
                this.$message.error("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(this.websocket)
                // 监听socket连接
                this.socket.onopen = this.open
                // 监听socket错误信息
                this.socket.onerror = this.error
                // 监听socket消息
                this.socket.onmessage = this.message
            }
        },
		open(){
            let text="socket连接成功，欢迎回来"
            this.broadcast(text);
            this.$message.success(text)
        },
        error(){
            this.$message.error("socket发生错误")
        },
        message(value){
            let that = this
            let data=JSON.parse(value.data)
			console.log(data)
            switch(data.type){
				case 'init':
					this.$request.post("/socket/bind",{client_id:data.client_id}).then((res)=>{
						console.log(res)
					})
					break;
				case 'text':
					this.broadcast(data.message);
                      this.$notify({
                        title: '有新的消息',
                        message: data.message,
                        });
					break;
				case 'withdraw':
					this.broadcast(data.message);
                    this.$notify({
                        title: data.title,
                        message: data.message,
                    });
                    this.$notify({
                        title: data.title,
                        message: data.message,
                        onClick:function(){
                            that.$router.push({ path: "/withdraw-details?id=" + data.relation_id});
                        }
                            
                    });
            
					break;
			}
        }
	}
}